<template>
  <div>
    <el-button type="primary" @click="openDialog()">新增安全威胁</el-button>
    <el-table :data="tableData" style="width: 100%; margin-top: 16px">
      <el-table-column type="index" :index="(index) => index + 1" label="编号" width="80" />
      <!-- <el-table-column prop="id" label="编号" width="80" /> -->
      <el-table-column prop="stState" label="隐患类别状态" :formatter="formatStatus" />
      <el-table-column prop="stDesc" label="描述" />
      <el-table-column prop="stName" label="隐患名字" />
      <el-table-column prop="createTime" label="上报时间" :formatter="formatDateTime" />

      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="openDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin-top: 16px"
      background
      layout="prev, pager, next, jumper, ->, total"
      :total="total"
      :page-size="pageSize"
      :current-page="currentPage"
      @current-change="handlePageChange"
    />
    <el-dialog :title="dialogTitle" v-model="dialogVisible">
      <el-form :model="form" label-width="90px">
        <el-form-item label="隐患名字">
          <el-input v-model="form.stName" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.stDesc" />
        </el-form-item>
        <el-form-item label="类别">
          <el-input v-model="form.stType" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.stState" placeholder="请选择状态">
            <el-option label="未处理" :value="0"></el-option>
            <el-option label="已处理" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上报时间">
          <el-date-picker
            v-model="form.createTime"
            type="datetime"
            placeholder="选择上报时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DDTHH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessageBox } from 'element-plus';
import {  postRequest, putRequest, deleteRequest } from '@/utils/request';

const tableData = ref([]);
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);
const dialogVisible = ref(false);
const dialogTitle = ref('新增安全威胁');
const form = reactive({
  id: null,
  stName: '',
  stDesc: '',
  stType: '',
  stState: '',
  createTime: ''
});

const formatStatus = (row, column, value) => {
  const statusMap = { 0: '未处理', 1: '已处理' };
  return statusMap[value] || value;
};

const formatDateTime = (row, column, value) => {
  if (!value) return '';
  // 将ISO时间格式转换为'YYYY-MM-DD HH:mm:ss'格式
  const date = new Date(value);
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
};

function fetchData() {
  postRequest('/securityThreat/getSecurityThreatByPage', { current: currentPage.value, size: pageSize.value }).then(res => {
    if (res && res.data) {
      tableData.value = Array.isArray(res.data.data.securityThreats) ? res.data.data.securityThreats : [];
      total.value = res.data.data.total || 0;
    } else {
      tableData.value = [];
      total.value = 0;
    }
  }).catch(error => {
    console.error('获取数据失败:', error);
    tableData.value = [];
    total.value = 0;
  });
}

function openDialog(row) {
  if (row) {
    dialogTitle.value = '编辑安全隐患';
    Object.assign(form, row);
    // 解析ISO日期格式并转换为Date对象
    form.createTime = row.createTime ? new Date(row.createTime) : null;
  } else {
    dialogTitle.value = '新增安全隐患';
    form.id = null;
    form.stName = '';
    form.stDesc = '';
    form.stType = '';
    form.stState = '';
    form.createTime = null;
  }
  dialogVisible.value = true;
}

function handleSubmit() {
  if (form.id) {
    putRequest('/securityThreat/updateSecurityThreatById', form).then(() => {
      dialogVisible.value = false;
      fetchData();
    });
  } else {
    postRequest('/securityThreat/addSecurityThreat', form).then(() => {
      dialogVisible.value = false;
      fetchData();
    });
  }
}

function handleDelete(id) {
  ElMessageBox.confirm('确定要删除该记录吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteRequest(`/securityThreat/deleteSecurityThreatById/${id}`).then(() => {
      fetchData();
    });
  }).catch(() => {});
}

function handlePageChange(page) {
  currentPage.value = page;
  fetchData();
}

onMounted(() => {
  fetchData();
});
</script>
